﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Net;
using Linxiao.SP.Workflow.AddCRMLead.Library.DynamicsCRMServices;
using System.ServiceModel.Security;

namespace Linxiao.SP.Workflow.AddCRMLead.Library
{
    public class DynamicsCRMContext: IDisposable
    {
        private OrganizationServiceClient organizationService;

        /// <summary>
        /// Create service client
        /// </summary>
        /// <param name="organizationServiceUrl"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        /// <param name="dynamicCrmServiceAccount"></param>
        public DynamicsCRMContext(string organizationServiceUrl, string username, string password, string domain, string dynamicCrmServiceAccount)
        {
            //Decrypted password
            string decryptedPassword = RSACryptoService.Decrypt(password, "LinxiaoKeyContainer");

            AddressHeaderCollection headers = new AddressHeaderCollection();           
            var endpoint = new EndpointAddress(new Uri(organizationServiceUrl), EndpointIdentity.CreateUpnIdentity(dynamicCrmServiceAccount), headers);
            var endpointBinding = GetServiceEndpointBinding("CustomBinding_IOrganizationService");

            organizationService = new OrganizationServiceClient(endpointBinding, endpoint);
            organizationService.ClientCredentials.Windows.ClientCredential = new NetworkCredential(username, decryptedPassword, domain);

        }

        /// <summary>
        /// Add a lead
        /// </summary>
        /// <param name="title"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="email"></param>
        /// <param name="telephone"></param>
        /// <param name="company"></param>
        /// <returns></returns>
        public Guid AddLead(string title, string firstName, string lastName, string email, string telephone, string company)
        {           
             Entity  lead = new Entity();
             lead.LogicalName = "lead";

             AttributeCollection attributeCollection = new AttributeCollection();
             lead.Attributes = attributeCollection;
             lead.Attributes.Add(new KeyValuePair<string, object>("subject", title));
             lead.Attributes.Add(new KeyValuePair<string,object>("firstname", firstName));
             lead.Attributes.Add(new KeyValuePair<string, object>("lastname", lastName));
             lead.Attributes.Add(new KeyValuePair<string, object>("emailaddress1", email));
             lead.Attributes.Add(new KeyValuePair<string, object>("telephone1", telephone));
             lead.Attributes.Add(new KeyValuePair<string, object>("companyname", company));

             return organizationService.Create(lead);
        }

        /// <summary>
        /// Cloase service
        /// </summary>
        public void Dispose()
        {
            if (organizationService!=null)
                organizationService.Close();
        }

        /// <summary>
        /// Configure endpoint binding
        /// </summary>
        /// <param name="bindingName"></param>
        /// <returns></returns>
        private static CustomBinding GetServiceEndpointBinding(string bindingName)   
        {   
            var endpointBinding = new CustomBinding   
                                    {   
                                        Name = bindingName   
                                    };   
  
            // Configure security binding   
            var securityElement = SecurityBindingElement.CreateSspiNegotiationBindingElement(true);   
            securityElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Default;  
            securityElement.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;   
            securityElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;   
            securityElement.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature;   
            securityElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;   
            securityElement.IncludeTimestamp = true;   
 
            var messageEncoding = new TextMessageEncodingBindingElement();   
            messageEncoding.ReaderQuotas.MaxStringContentLength = int.MaxValue;   
            messageEncoding.ReaderQuotas.MaxArrayLength = int.MaxValue;   
            messageEncoding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;   
  
            var transport = new HttpTransportBindingElement   
                                        {   
                                            MaxBufferSize = int.MaxValue,   
                                            MaxReceivedMessageSize = int.MaxValue   
                                        };   
 
            // Add the SymmetricSecurityBindingElement to the BindingElementCollection.   
            endpointBinding.Elements.Add(securityElement);   
            endpointBinding.Elements.Add(messageEncoding);   
            endpointBinding.Elements.Add(transport);   
  
            return endpointBinding;   
        }  

    }
}
